<?php
    
    if (!isset($_GET['friends'])) {
        die("Error");
    }
    
	include_once "include/constants.php";
	include_once "util_suggest_algo.php";
	
    if (!defined('IS_AJAX')) {
        define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
    }

    $suggestion = suggest($_GET['friends']);
    $movieIds = "";

    foreach ($suggestion as $movieId => $rating) {
        $movieIds .= $movieId . ",";
    }
    $movieIds = substr_replace($movieIds, "", -1);
    try {
        $conn = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME, DB_USER, DB_PASS);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    
       
        $stmt = $conn->prepare('select m.movieid, title, year, imdbid,
                                GROUP_CONCAT(genre SEPARATOR ", ") as genre, taglinetext
                                from movies m
                                left outer join genres g on (m.movieid = g.movieid)
                                left outer join taglines t on (m.movieid = t.movieid)
                                where m.movieId in (' . $movieIds . ')
                                group by m.movieid;');
        $stmt->execute();
        
        $queryResult = array();
        while ($moviedata = $stmt->fetch()) {
            //$moviedata['title'] = substr($moviedata['title'], 0, strlen($moviedata['title']) - 7);
			$pattern = '/(?P<title>.+)\(\d{4}\/?\w*\)/';
			preg_match($pattern, $moviedata['title'], $matches);
			$moviedata['title'] = $matches['title'];
            $queryResult[$moviedata['movieid']] = $moviedata;
        }
                
        $result = array();
        foreach ($suggestion as $movieId => $rating) {
            $result[] = array("movieid" => $movieId, "rating" => $rating, "moviedata" => $queryResult[$movieId]);
        }
        
        if (IS_AJAX) echo json_encode($result);
        else $chosenMovie = $result;
        
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
?>
